import pool from '../database/index.js'
import jwt from 'jsonwebtoken'
import md5 from 'md5'



/**注册 */
export const register = async(req,res)=>{
    const { account,password } = req.body 
    try{
       const [result,fields] = await pool.query(`SELECT * FROM user WHERE account=${account}`) 
       if(result.length) return res.status(403).send({ msg:'请求失败',code:403,data:{ message:'此账号已注册' } })
       await pool.execute(`INSERT INTO user (account,password) 
       VALUES ('${account}','${md5(password)}')`)
       res.send({ msg:'请求成功',code:200,data:{ message:'注册成功' } })
    }catch(error){
       console.log(`接口${req.path}出现错误,错误为${error}`)
       res.status(400).send({ msg:'请求失败',code:400,data:{ message:'注册失败' } })
    }

}

/**登录 */
export const login = async(req,res)=>{
    const { account,password } = req.body
    const [result,fields] = await pool.execute(`SELECT id,account FROM user 
        WHERE account='${account}' AND password='${md5(password)}' AND disabled=0`)
    if(!result.length) return res.status(404).send({ msg:'登陆失败',code:404,data:{ message:'用户不存在' }  })
    const { id } = result[0]    
    const token = jwt.sign({ id,account },process.env.SecretKey,{ expiresIn: '24h' })
    res.send({ msg:'请求成功',code:200,data:{ message:'登陆成功',token,info:result[0] } })
}